package com.jay.lang.clazz.ifstat;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

//need to install ifstat in your system first, and for window, must set path for this command
public class IfStat {
	public static void main(String[] args) throws IOException,
			InterruptedException {

		System.out.println("----");
		System.out.println(CmdIfStat.executeCommand(new String[] { "ifstat" },
				null, null));

		System.out.println("----");
	}

	public static final class CmdIfStat {

		private CmdIfStat() {
		}

		public static String executeCommand(String[] cmd, String[] env, File dir)
				throws IOException, InterruptedException {
			Process ps;
			if (dir == null) {
				ps = Runtime.getRuntime().exec(cmd, env);
			} else {
				ps = Runtime.getRuntime().exec(cmd, env, dir);
			}
			Scanner scanner1 = new Scanner(ps.getInputStream());
			Scanner scanner2 = new Scanner(ps.getErrorStream());
			Thread.sleep(5000);
			ps.destroy();
			StringBuilder result = new StringBuilder();

			result.append(scanner1.nextLine());
			result.append(System.getProperty("line.separator"));
			result.append(scanner1.nextLine());
			result.append(System.getProperty("line.separator"));

			float in = 0, out = 0;
			while (scanner1.hasNextLine()) {
				String line = scanner1.nextLine();
				String[] s = line.split("\\s+");
				in += Float.parseFloat(s[1]);
				out += Float.parseFloat(s[2]);
				result.append(line);
				result.append(System.getProperty("line.separator"));
			}
			result.append("Total In: " + in);
			result.append(System.getProperty("line.separator"));
			result.append("Total Out: " + out);
			result.append(System.getProperty("line.separator"));
			while (scanner2.hasNextLine()) {
				result.append(scanner2.nextLine());
				result.append(System.getProperty("line.separator"));
			}
			scanner1.close();
			scanner2.close();
			return result.toString();
		}
	}
}
